package com.mikasa.spring.convert;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

/**
 * 文本消息转换类
 * @author mikasa
 */
public class TextMessageConverter implements MessageConverter {

	/**
	 * java对象 转换为 message对象
	 * @param object
	 * @param messageProperties
	 * @return
	 * @throws MessageConversionException
	 */
	@Override
	public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
		return new Message(object.toString().getBytes(), messageProperties);
	}

	/**
	 * message对象 转换为 java对象
	 * @param message
	 * @return
	 * @throws MessageConversionException
	 */
	@Override
	public Object fromMessage(Message message) throws MessageConversionException {
		String contentType = message.getMessageProperties().getContentType();
		// 消息发送需设置 messageProperties.setContentType 为text/.. 详细见 ApplicationTest的 testSendMessage2()方法
		if(null != contentType && contentType.contains("text")) {
			return new String(message.getBody());
		}
		return message.getBody();
	}

}
